/// 主页面
/// 显示聊天列表和底部导航栏
library;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:go_router/go_router.dart';
import 'package:chat_project/providers/auth_provider.dart';
import 'package:chat_project/providers/chat_provider.dart';
import 'package:chat_project/providers/user_provider.dart';
import 'package:chat_project/config/theme_config.dart';
import 'package:chat_project/widgets/conversation_list.dart';
import 'package:chat_project/widgets/contact_list.dart';
import 'package:chat_project/models/conversation_model.dart';
import 'package:chat_project/models/user_model.dart';
import 'package:chat_project/services/api_service.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _currentIndex = 0;
  
  // 底部导航项目
  final List<_NavigationItem> _navigationItems = [
    _NavigationItem(
      icon: Icons.chat,
      label: '聊天',
      page: const _ChatTab(),
    ),
    _NavigationItem(
      icon: Icons.people,
      label: '联系人',
      page: const _ContactsTab(),
    ),
    _NavigationItem(
      icon: Icons.explore,
      label: '发现',
      page: const _DiscoverTab(),
    ),
    _NavigationItem(
      icon: Icons.person,
      label: '我的',
      page: const _ProfileTab(),
    ),
  ];

  @override
  void initState() {
    super.initState();
    // 在初始化时加载聊天数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final chatProvider = Provider.of<ChatProvider>(context, listen: false);
      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      final userProvider = Provider.of<UserProvider>(context, listen: false);
      
      if (authProvider.isAuthenticated && authProvider.user != null) {
        chatProvider.init(authProvider.user!);
        // 加载联系人列表
        userProvider.loadContacts();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _navigationItems[_currentIndex].page,
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        selectedItemColor: ThemeConfig.primaryColor,
        unselectedItemColor: ThemeConfig.textSecondaryColor,
        type: BottomNavigationBarType.fixed,
        items: _navigationItems.map((item) => BottomNavigationBarItem(
          icon: Icon(item.icon),
          label: item.label,
        )).toList(),
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}

// 导航项目模型
class _NavigationItem {
  final IconData icon;
  final String label;
  final Widget page;

  _NavigationItem({
    required this.icon,
    required this.label,
    required this.page,
  });
}

// 聊天选项卡
class _ChatTab extends StatelessWidget {
  const _ChatTab();

  @override
  Widget build(BuildContext context) {
    final chatProvider = Provider.of<ChatProvider>(context);
    
    return Scaffold(
      appBar: _buildAppBar(context),
      body: RefreshIndicator(
        onRefresh: () => chatProvider.loadConversations(),
        child: const ConversationList(),
      ),
    );
  }
  
  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      title: const Text('聊天'),
      actions: [
        IconButton(
          icon: const Icon(Icons.search),
          tooltip: '搜索用户',
          onPressed: () => _showSearchUserDialog(context),
        ),
        IconButton(
          icon: const Icon(Icons.account_circle),
          tooltip: '个人中心',
          onPressed: () {
            // 显示个人资料
          },
        ),
        IconButton(
          icon: const Icon(Icons.logout),
          tooltip: '注销',
          onPressed: () {
            final authProvider = Provider.of<AuthProvider>(context, listen: false);
            authProvider.logout();
          },
        ),
      ],
    );
  }

  void _showSearchUserDialog(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    final searchController = TextEditingController();
    
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('搜索用户'),
        content: Container(
          width: double.maxFinite,
          constraints: BoxConstraints(
            maxHeight: MediaQuery.of(context).size.height * 0.6,
          ),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: searchController,
                  decoration: const InputDecoration(
                    labelText: '用户名或邮箱',
                    hintText: '输入关键词搜索用户',
                    prefixIcon: Icon(Icons.search),
                  ),
                  onSubmitted: (_) {
                    if (searchController.text.isNotEmpty) {
                      userProvider.searchUsers(searchController.text);
                    }
                  },
                ),
                const SizedBox(height: 16),
                Consumer<UserProvider>(
                  builder: (ctx, provider, _) {
                    if (provider.isLoading) {
                      return const Center(child: CircularProgressIndicator());
                    }
                    
                    if (provider.error != null) {
                      return Text(
                        '搜索失败: ${provider.error}',
                        style: const TextStyle(color: Colors.red),
                      );
                    }
                    
                    if (provider.searchResults.isEmpty && searchController.text.isNotEmpty) {
                      return const Text('没有找到匹配的用户');
                    }
                    
                    if (provider.searchResults.isEmpty && searchController.text.isEmpty) {
                      return const Text('请输入关键词搜索用户');
                    }
                    
                    return Container(
                      constraints: BoxConstraints(
                        maxHeight: MediaQuery.of(context).size.height * 0.4,
                      ),
                      child: ListView.builder(
                        shrinkWrap: true,
                        itemCount: provider.searchResults.length,
                        itemBuilder: (ctx, index) {
                          final user = provider.searchResults[index];
                          return ListTile(
                            leading: CircleAvatar(
                              // 使用更安全的图片加载方式
                              backgroundColor: Colors.blue.shade100,
                              // 使用更安全的图片加载方式
                              child: Text(user.username.isNotEmpty ? user.username[0].toUpperCase() : '?'),
                            ),
                            title: Text(user.username),
                            subtitle: Text(user.email),
                            trailing: IconButton(
                              icon: const Icon(Icons.person_add),
                              tooltip: '添加联系人',
                              onPressed: () => _addContact(context, user),
                            ),
                          );
                        },
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              userProvider.clearError();
              Navigator.of(context).pop();
            },
            child: const Text('关闭'),
          ),
          TextButton(
            onPressed: () {
              if (searchController.text.isNotEmpty) {
                userProvider.searchUsers(searchController.text);
              }
            },
            child: const Text('搜索'),
          ),
        ],
      ),
    );
  }

  void _addContact(BuildContext context, User user) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    final chatProvider = Provider.of<ChatProvider>(context, listen: false);
    
    try {
      // 显示加载对话框
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (ctx) => const AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('正在添加联系人...'),
            ],
          ),
        ),
      );
      
      // 添加联系人
      final result = await userProvider.addContact(user.id);
      
      // 添加成功后关闭对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }
      
      // 刷新对话列表
      chatProvider.loadConversations();
      
      // 显示成功消息
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已成功添加 ${user.username} 为联系人')),
        );
        
        // 关闭搜索对话框
        Navigator.of(context).pop();
      }
    } catch (e) {
      // 添加失败，关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
        
        // 显示错误消息，更友好的处理已存在联系人的情况
        final String errorMessage = e.toString().contains('已经是您的联系人') 
            ? '${user.username} 已经是您的联系人' 
            : '添加联系人失败: $e';
            
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(errorMessage),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}

// 联系人选项卡
class _ContactsTab extends StatelessWidget {
  const _ContactsTab();

  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context);
    
    // 在初始化时，加载联系人列表
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!userProvider.isLoading && userProvider.contacts.isEmpty) {
        userProvider.loadContacts();
      }
    });
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('联系人'),
        backgroundColor: ThemeConfig.primaryColor,
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.person_add),
            onPressed: () {
              // 显示添加联系人对话框
              _showAddContactDialog(context);
            },
          ),
        ],
      ),
      body: ContactList(
        onContactSelected: (contact) {
          // 创建或获取对话，然后导航到聊天详情页
          _startChatWithContact(context, contact);
        },
      ),
    );
  }
  
  // 显示添加联系人对话框
  void _showAddContactDialog(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    final searchController = TextEditingController();
    
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('添加联系人'),
        content: Container(
          width: double.maxFinite,
          constraints: BoxConstraints(
            maxHeight: MediaQuery.of(context).size.height * 0.6,
          ),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: searchController,
                  decoration: const InputDecoration(
                    labelText: '用户名或邮箱',
                    hintText: '输入关键词搜索用户',
                    prefixIcon: Icon(Icons.search),
                  ),
                  onSubmitted: (_) {
                    if (searchController.text.isNotEmpty) {
                      userProvider.searchUsers(searchController.text);
                    }
                  },
                ),
                const SizedBox(height: 16),
                Consumer<UserProvider>(
                  builder: (ctx, provider, _) {
                    if (provider.isLoading) {
                      return const Center(child: CircularProgressIndicator());
                    }
                    
                    if (provider.error != null) {
                      return Text(
                        '搜索失败: ${provider.error}',
                        style: const TextStyle(color: Colors.red),
                      );
                    }
                    
                    if (provider.searchResults.isEmpty && searchController.text.isNotEmpty) {
                      return const Text('没有找到匹配的用户');
                    }
                    
                    if (provider.searchResults.isEmpty && searchController.text.isEmpty) {
                      return const Text('请输入关键词搜索用户');
                    }
                    
                    return Container(
                      constraints: BoxConstraints(
                        maxHeight: MediaQuery.of(context).size.height * 0.4,
                      ),
                      child: ListView.builder(
                        shrinkWrap: true,
                        itemCount: provider.searchResults.length,
                        itemBuilder: (ctx, index) {
                          final user = provider.searchResults[index];
                          return ListTile(
                            leading: CircleAvatar(
                              backgroundColor: Colors.blue.shade100,
                              child: Text(user.username.isNotEmpty ? user.username[0].toUpperCase() : '?'),
                            ),
                            title: Text(user.username),
                            subtitle: Text(user.email),
                            trailing: IconButton(
                              icon: const Icon(Icons.person_add),
                              tooltip: '添加联系人',
                              onPressed: () {
                                _addContactFromContactsTab(context, user);
                              },
                            ),
                          );
                        },
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              userProvider.clearError();
              Navigator.of(context).pop();
            },
            child: const Text('关闭'),
          ),
          TextButton(
            onPressed: () {
              if (searchController.text.isNotEmpty) {
                userProvider.searchUsers(searchController.text);
              }
            },
            child: const Text('搜索'),
          ),
        ],
      ),
    );
  }
  
  void _addContactFromContactsTab(BuildContext context, User user) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    final chatProvider = Provider.of<ChatProvider>(context, listen: false);
    
    try {
      // 显示加载对话框
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (ctx) => const AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('正在添加联系人...'),
            ],
          ),
        ),
      );
      
      // 添加联系人
      final result = await userProvider.addContact(user.id);
      
      // 添加成功后关闭对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }
      
      // 刷新对话列表
      chatProvider.loadConversations();
      
      // 显示成功消息
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已成功添加 ${user.username} 为联系人')),
        );
        
        // 关闭搜索对话框
        Navigator.of(context).pop();
      }
    } catch (e) {
      // 添加失败，关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
        
        // 显示错误消息，更友好的处理已存在联系人的情况
        final String errorMessage = e.toString().contains('已经是您的联系人') 
            ? '${user.username} 已经是您的联系人' 
            : '添加联系人失败: $e';
            
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(errorMessage),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 开始与联系人聊天
  void _startChatWithContact(BuildContext context, User contact) async {
    final chatProvider = Provider.of<ChatProvider>(context, listen: false);
    final apiService = ApiService();
    
    try {
      // 显示加载指示器
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (ctx) => const AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('正在加载对话...'),
            ],
          ),
        ),
      );
    
      // 查找现有对话或创建新对话
      Conversation? conversation;
      String conversationId;
      
      // 首先尝试在本地查找
      try {
        conversation = chatProvider.conversations.firstWhere(
          (conv) => conv.contact.id == contact.id,
        );
        conversationId = conversation.id;
        print('在本地找到已存在的对话: $conversationId 与联系人 ${contact.id}');
      } catch (e) {
        // 本地没有找到，调用API创建或获取
        print('本地未找到对话，创建新对话 与联系人 ${contact.id}');
        try {
          final result = await apiService.getOrCreateConversation(contact.id);
          conversationId = result['_id'] as String;
          
          // 创建临时对话对象并添加到对话列表中
          conversation = Conversation(
            id: conversationId,
            contact: contact,
          );
          print('创建了新对话: $conversationId');
          
          // 强制刷新会话列表，确保新创建的会话被加载
          await chatProvider.loadConversations();
        } catch (error) {
          print('创建对话失败: $error');
          // 使用临时ID作为备选
          conversationId = 'temp_conv_${contact.id}_${DateTime.now().millisecondsSinceEpoch}';
          print('使用临时对话ID: $conversationId');
        }
      }
      
      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      
        // 获取联系人ID（确保是字符串而非对象）
        final contactId = contact.id;
        print('联系人ID: $contactId');
        
        // 选择会话并加载消息
        await chatProvider.selectConversation(conversationId, contactId);
        
        // 使用GoRouter的push方法
        context.push('/chat/$conversationId/$contactId');
        print('已导航至聊天页面: /chat/$conversationId/$contactId');
      }
    } catch (e) {
      // 错误处理
      if (context.mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
        
        // 显示错误信息
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('加载对话失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}

// 发现选项卡
class _DiscoverTab extends StatelessWidget {
  const _DiscoverTab();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('发现'),
        backgroundColor: ThemeConfig.primaryColor,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: ListView(
        children: [
          _buildDiscoverItem(
            icon: Icons.group,
            title: '群聊',
            onTap: () {},
          ),
          _buildDiscoverItem(
            icon: Icons.campaign,
            title: '频道',
            onTap: () {},
          ),
          _buildDiscoverItem(
            icon: Icons.person_search,
            title: '附近的人',
            onTap: () {},
          ),
          _buildDiscoverItem(
            icon: Icons.tag,
            title: '标签',
            onTap: () {},
          ),
        ],
      ),
    );
  }

  Widget _buildDiscoverItem({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: ThemeConfig.primaryColor,
      ),
      title: Text(title),
      trailing: const Icon(
        Icons.chevron_right,
        color: ThemeConfig.textSecondaryColor,
      ),
      onTap: onTap,
    );
  }
}

// 个人资料选项卡
class _ProfileTab extends StatelessWidget {
  const _ProfileTab();

  @override
  Widget build(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context);
    final user = authProvider.user;

    return Scaffold(
      appBar: AppBar(
        title: const Text('我的'),
        backgroundColor: ThemeConfig.primaryColor,
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () {
              // 导航到设置页面
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 用户资料卡片
            _buildProfileCard(context, user?.username ?? '用户', user?.email ?? ''),
            
            const SizedBox(height: 20),
            
            // 设置选项
            _buildSettingItem(
              icon: Icons.image,
              title: '我的相册',
              onTap: () {},
            ),
            _buildSettingItem(
              icon: Icons.favorite,
              title: '我的收藏',
              onTap: () {},
            ),
            _buildSettingItem(
              icon: Icons.wallet,
              title: '我的钱包',
              onTap: () {},
            ),
            _buildSettingItem(
              icon: Icons.style,
              title: '主题设置',
              onTap: () {},
            ),
            
            const SizedBox(height: 20),
            
            // 退出登录按钮
            Padding(
              padding: const EdgeInsets.all(16),
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  foregroundColor: Colors.white,
                  minimumSize: const Size.fromHeight(50),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                onPressed: () async {
                  // 显示确认对话框
                  final confirm = await showDialog<bool>(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: const Text('确认退出'),
                      content: const Text('您确定要退出登录吗？'),
                      actions: [
                        TextButton(
                          onPressed: () => Navigator.pop(context, false),
                          child: const Text('取消'),
                        ),
                        TextButton(
                          onPressed: () => Navigator.pop(context, true),
                          child: const Text('确定'),
                        ),
                      ],
                    ),
                  );
                  
                  if (confirm == true) {
                    await authProvider.logout();
                    if (context.mounted) {
                      // 返回登录页
                      context.go('/login');
                    }
                  }
                },
                child: const Text('退出登录'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProfileCard(BuildContext context, String username, String email) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(24),
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        children: [
          // 头像
          CircleAvatar(
            radius: 50,
            backgroundColor: ThemeConfig.primaryColor.withOpacity(0.1),
            child: Text(
              username.isNotEmpty ? username[0].toUpperCase() : 'U',
              style: const TextStyle(
                fontSize: 36,
                fontWeight: FontWeight.bold,
                color: ThemeConfig.primaryColor,
              ),
            ),
          ),
          const SizedBox(height: 16),
          
          // 用户名
          Text(
            username,
            style: const TextStyle(
              fontSize: 22,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          
          // 邮箱
          Text(
            email,
            style: const TextStyle(
              fontSize: 16,
              color: ThemeConfig.textSecondaryColor,
            ),
          ),
          const SizedBox(height: 16),
          
          // 编辑资料按钮
          OutlinedButton.icon(
            icon: const Icon(Icons.edit),
            label: const Text('编辑资料'),
            style: OutlinedButton.styleFrom(
              foregroundColor: ThemeConfig.primaryColor,
              side: const BorderSide(color: ThemeConfig.primaryColor),
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            onPressed: () {
              // 导航到编辑资料页面
            },
          ),
        ],
      ),
    );
  }

  Widget _buildSettingItem({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: ThemeConfig.primaryColor,
      ),
      title: Text(title),
      trailing: const Icon(
        Icons.chevron_right,
        color: ThemeConfig.textSecondaryColor,
      ),
      onTap: onTap,
    );
  }
} 
